package com.mgg.user.controller.user;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import com.mgg.common.client.order.OrderApiClient;
import com.mgg.common.client.pay.PayClient;
import com.mgg.common.entity.ValidateCode;
import com.mgg.common.enums.UserRoleEnum;
import com.mgg.common.exception.ServiceException;
import com.mgg.common.util.DateUtils;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.common.util.ValidateCodeUtils;
import com.mgg.common.vo.ResultVO;
import com.mgg.common.entity.UserDO;
import com.mgg.user.enums.UserResultEnum;
import com.mgg.user.service.BaseUserService;
import com.mgg.user.service.user.UserActivityService;
import com.mgg.user.service.user.UserService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("act")
public class UserActivityController {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private UserService userService;

	@Autowired
    private BaseUserService baseUserService;

	@Autowired
	private UserActivityService userActivityService;
	
	@Autowired
	private RedisTemplate<String,Object> redisTemplate;
	
	@Autowired
	private OrderApiClient orderApiClient;
	
	@Autowired
	private PayClient payClient;
	
	@Autowired
    @Qualifier("poolTaskExecutor")
    private Executor executor;
		
	@GetMapping("/code/info")
	public Object getActCodeInfo(@RequestParam String mobile, @RequestParam("sms_code") String smsCode, @RequestParam("act_code") String actCode) {
        Map<String,String> actCodeMap =  userActivityService.getActCodeInfo(actCode);
        checkActCode(smsCode, mobile, actCodeMap);
		return ResultVOUtil.success();
	}
	
	/**
	 * 激活码激活店主
	 * @param mobile
	 * @param smsCode
	 * @param actCode
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/active")
	public Object activeShopkeeper(@RequestParam String mobile, @RequestParam("sms_code") String smsCode, @RequestParam("act_code") String actCode) {
		Map<String,String> actCodeMap =  userActivityService.getActCodeInfo(actCode);
		checkActCode(smsCode, mobile, actCodeMap);
		String shopCode = actCodeMap.get("shop_code");
        //获取用户信息
        UserDO superUser = baseUserService.getUserByShopCode(shopCode);
        if (superUser == null) {
            throw new ServiceException(UserResultEnum.SHOP_CODE_ERROR.getCode(), UserResultEnum.SHOP_CODE_ERROR.getMessage());
        }
        String superId = superUser.getUserId();
        UserDO user = getUser(mobile,shopCode,superId);
        String userId = user.getUserId();
		//修改激活码状态
		Integer count = userActivityService.updateActCode(null, null, actCode, "1", "2", userId, mobile, DateUtils.getTime());
		if (count == 0) {
			return ResultVOUtil.error(UserResultEnum.ACT_CODE_ERROR);
		}
		userService.vipToShopKeeper(userId, shopCode, DateUtils.getTime(),"使用激活码成为店主");
		return ResultVOUtil.success();
	}



	/**
	 * 千千氏门店激活码激活店主
	 * @param mobile
	 * @param smsCode
	 * @param shopCode
	 * @param actCode
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/qqs/active")
	public Object qqsActiveShopkeeper(@RequestParam String mobile, @RequestParam("sms_code") String smsCode, 
			@RequestParam("shop_code") String shopCode, @RequestParam("act_code") String actCode) {
		Map<String,String> actCodeMap =  userActivityService.getActCodeInfo(actCode);
		checkActCode(smsCode, mobile, actCodeMap);
		String storeCode = actCodeMap.get("store_code");
		
		//获取用户信息
        UserDO superUser = baseUserService.getUserByShopCode(shopCode);
        if (superUser == null) {
            throw new ServiceException(UserResultEnum.SHOP_CODE_ERROR.getCode(), UserResultEnum.SHOP_CODE_ERROR.getMessage());
        }
        String superId = superUser.getUserId();
        UserDO user = getUser(mobile,shopCode,superId);
		String userId = user.getUserId();
		
		//修改激活码状态
		Integer count = userActivityService.updateActCode(null, shopCode, actCode, "1", "2", userId, mobile, DateUtils.getTime());
		if (count == 0) {
            return ResultVOUtil.error(UserResultEnum.ACT_CODE_ERROR);
		}
		userService.vipToShopKeeper(userId, shopCode, DateUtils.getTime(),"使用激活码成为店主");
		
		CompletableFuture
		.runAsync(() ->
		{
			try {
				//生成订单
				ResultVO result = orderApiClient.addStoreOrder(userId, shopCode, storeCode);
				if (!"100".equals(result.getCode())) {
					throw new Exception("订单生成失败");
				}
				Map<String,Object> map = (Map<String, Object>) result.getData();
				String orderId = (String) map.get("order_id");
				//订单返利
				payClient.sendRegistShopkeeperOrderRebate(orderId,superId);
			} catch (Exception e1) {
				log.error(e1.getMessage(), e1);
				log.error("订单返利失败， userId = {},  shopCode = {},  storeCode = {}", userId, shopCode, storeCode);
			}
		}
		, executor);
		return ResultVOUtil.success();
	}


	private void checkActCode(String smsCode, String mobile, Map<String, String> actCodeMap) {
		//检验验证码
		ValidateCode validateCode = (ValidateCode) redisTemplate.opsForValue().get("code:sms:" + mobile);
		ValidateCodeUtils.checkCode(smsCode,validateCode);

		//激活码校验
		if (MapUtils.isEmpty(actCodeMap)) {
			throw new ServiceException(UserResultEnum.ACT_CODE_ERROR.getCode(), UserResultEnum.ACT_CODE_ERROR.getMessage());
		}
		if ("2".equals(actCodeMap.get("status"))) {
			throw new ServiceException(UserResultEnum.ACT_CODE_USED.getCode(), UserResultEnum.ACT_CODE_USED.getMessage());
		}
	}

	private UserDO getUser(String mobile, String shopCode, String superId) {
		UserDO user = baseUserService.getUserByPhone(mobile);
		if (user == null) {
			// 新用户，创建用户信息
			userService.saveVipUser(mobile,shopCode,null, superId);
			user = baseUserService.getUserByPhone(mobile);
		} else if (user != null && !UserRoleEnum.VIP.getCode().equals(user.getRoleCode())) {
            throw new ServiceException(UserResultEnum.ACT_USER_ERROR.getCode(), UserResultEnum.ACT_USER_ERROR.getMessage());
		} 	
		return user;
	}

}
